// +---------------------------------------------------
// | 字符串转成日期类型
// | 格式 MM/dd/YYYY MM-dd-YYYY YYYY/MM/dd YYYY-MM-dd
// +---------------------------------------------------
export function stringToDate(DateStr) {
  try {
    const converted = Date.parse(DateStr)
    let myDate = new Date(converted)
    if (isNaN(myDate)) {
      // var delimCahar = DateStr.indexOf('/')!=-1?'/':'-';
      const arys = DateStr.split('-')
      myDate = new Date(arys[0], --arys[1], arys[2])
    }
    return myDate && myDate.getTime()
  } catch (e) {
    console.error(e)
    return null
  }
}

/**
 * Created by jiachenpan on 16/11/18.
 */

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * 将秒转换为对应的秒、分钟、小时
 */
export function formatSeconds(seconds) {
  if (typeof seconds !== 'number') {
    return ''
  }
  if (seconds < 60) {
    return `${seconds}秒`
  }
  if (seconds < 3600) {
    const sec = seconds % 60
    const secText = sec > 0 ? `${sec}秒` : ''
    return `${Math.floor(seconds / 60)}分${secText}`
  }
  const hour = Math.floor(seconds / 3600)

  const min = Math.floor(seconds % 3600 / 60)
  const minText = min > 0 ? `${min}分` : ''

  const sec = seconds % 3600 % 60
  const secText = sec > 0 ? `${sec}秒` : ''
  return `${hour}小时${minText}${secText}`
}

// 格式化时间
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

export function formatDate(date, fmt) {
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    'S': date.getMilliseconds()
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  }
  return fmt
}

/**
 *处理上送时间
 * @param timeStr 如：2019-08-21 22:20:17
 * @returns 如：2019-08-21T22:20:17
 */
export function dealRequestTime(timeStr) {
  if (timeStr.includes(' ')) {
    return timeStr.replace(' ', 'T')
  }
  return timeStr
}

/**
 * 处理响应时间
 * @param timeStr 如：2019-08-21T22:20:17
 * @returns 如：2019-08-21 22:20:17
 */
export function dealResponseTime(timeStr) {
  if (timeStr && timeStr.includes('T')) {
    return timeStr.replace('T', ' ')
  }
  return timeStr
}

/**
 * 将2019-01-23 格式时间转换成 2019.01.23 格式
 * @param {*} timeStr : 2019-01-23
 * @returns string
 */
export function dotDateString(timeStr) {
  if (timeStr && timeStr.includes('-')) {
    return timeStr.replace(/-/g, '.')
  }
  return timeStr
}

/**
 * 将2019-12-23T13:23:45 格式的时间转换成 2019.12.23格式
 * @param {*} timeStr : 2019-01-23 12:23:33
 * @returns string
 */
export function dotYMD(timeStr) {
  if (!timeStr) return timeStr
  if (timeStr && timeStr.includes('T')) {
    return timeStr.split('T')[0].replace(/-/g, '.')
  }
  if (timeStr && timeStr.includes(' ')) {
    return timeStr.split(' ')[0].replace(/-/g, '.')
  }
  return timeStr.replace(/-/g, '.')
}

/**
 * 将视频时长秒转换为对应的时:分:秒
 */
export function formatVideoSeconds(seconds) {
  if (typeof seconds !== 'number') {
    return ''
  }
  var b = ''
  var h = parseInt(seconds / 3600)
  var m = parseInt(seconds % 3600 / 60)
  var s = parseInt(seconds % 3600 % 60)
  if (h > 0) {
    h = h < 10 ? '0' + h : h
    b += h + ':'
  }
  m = m < 10 ? '0' + m : m
  s = s < 10 ? '0' + s : s
  b += m + ':' + s
  return b
}

/**
 * 将2019-12-23T13:23:45 转化成 2019/12/23 13:23
 */
export function delTimeToSlantTime(timeStr) {
  if (!timeStr) return ''
  return timeStr.substring(0, 16).replace(/-/g, '/').replace('T', ' ')
}

/**
 *
 * 当天日期就显示，非当天日期显示年月日时分
 */
export function formatCommentTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 60) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else {
    if (option) {
      return parseTime(time, option)
    } else {
      return parseTime(time)
    }
  }
}

export function parseWeek(time) {
  if (!time) {
    return null
  }
  const day = time.getDay()
  return '周' + ['日', '一', '二', '三', '四', '五', '六'][day]
}
